package com.lzp.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @description: 跨域配置
 * @author: lzp
 * @createTime: 2021-10-20 07:16
 **/
@Configuration
public class CorsConfig  implements WebMvcConfigurer {

    /**
     * 设置跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有资源
                .allowedOrigins("http://localhost:8080","http://49.232.170.99:80","http://192.168.233.130:8080") // "*"
                .allowCredentials(true) // 允许发送cookie
                .allowedHeaders("*")
                .allowedMethods("*");
    }

    /**
     * 跨域的另一种写法
     *
     * @return
     */
//    @Bean
    public CorsFilter corsFilter() {
        // Cors配置
        CorsConfiguration config = new CorsConfiguration();
        // 1. 设置请求域名
        config.addAllowedOrigin("http://localhost:8080"); // 本地ip
        config.addAllowedOrigin("http://192.168.233.130:8080"); // 虚拟机
        config.addAllowedOrigin("http://49.232.170.99"); // 外网ip
        config.addAllowedOrigin("*"); // 任意

        // 2. 设置允许的header
        config.addAllowedHeader("*");

        // 3. 设置允许请求的方法
        config.addAllowedMethod("*");

        // 4. 设置是否发送cookie
        config.setAllowCredentials(true);

        // 为URL添加路由
        UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
        corsSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(corsSource);
    }
}
